package com.qiyu.common.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * bitmap存储id，日后判断是否id存在
 *
 * @author linhao
 * @date 2019/9/16
 * @Version V1.0
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SysBitMapDTO implements Serializable {

    private static final long serialVersionUID = 2839184582093475512L;

    private byte[] bytes;
    private int initSize;

    public SysBitMapDTO(int size) {
        if (size <= 0) {
            return;
        }
        initSize = size / (8) + 1;
        bytes = new byte[initSize];
    }

    /**
     * 设置值
     *
     * @param number
     */
    public void set(int number) {
        //相当于对一个数字进行右移动3位，相当于除以8
        int index = number >> 3;
        //相当于 number % 8 获取到byte[index]的位置
        int position = number & 0x07;
        //进行|或运算  参加运算的两个对象只要有一个为1，其值为1。
        bytes[index] |= 1 << position;
    }


    /**
     * 是否包含值
     *
     * @param number
     * @return
     */
    public boolean contain(int number) {
        int index = number >> 3;
        int position = number & 0x07;
        return (bytes[index] & (1 << position)) != 0;
    }

    public static void main(String[] args) {
        SysBitMapDTO myBitMap = new SysBitMapDTO(10000000);
        for(int i=0;i<10000000;i++){
            myBitMap.set(i);
        }
        System.out.println(myBitMap.contain(10000000));
    }

}
